﻿namespace Home
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Home.Repository;
    using Newtonsoft.Json.Linq;

    public class WebsiteVisitCommand : WebsiteCommand
    {
        protected override string EntitySetName
        {
            get { return "Visits"; }
        }

        protected override string OptimizationCategory
        {
            get { return "Visit"; }
        }

        protected override WebsiteSynchronizationType SynchronizationType
        {
            get { return WebsiteSynchronizationType.OptimizationVisit; }
        }

        protected override void AddEntity(ServiceDbContext database, WebsiteEntity entity)
        {
            database.Visits.Add((OptimizationVisit)entity);
        }

        protected override void FulfillEntity(JToken json, WebsiteEntity entity)
        {
            var obj = (OptimizationVisit)entity;
            obj.VisitorId = (Guid)json["VisitorId"];
            obj.RegisteredUserId = (Guid?)json["RegisteredUserId"];
            obj.Category = (string)json["Category"];
            obj.CategoryDetail = (string)json["CategoryDetail"];
            obj.Url = (string)json["Url"];
            obj.Referer = (string)json["Referer"];
            obj.Agent = (string)json["Agent"];
            obj.Geolocation = (string)json["Geolocation"];
            obj.Language = (string)json["Language"];
            obj.Platform = (string)json["Platform"];
        }

        protected override bool TryGetEntity(ServiceDbContext database, Guid websiteId, out WebsiteEntity entity)
        {
            entity = database.Visits.FirstOrDefault(e => e.WebsiteId == websiteId);

            if (entity == null)
            {
                entity = new OptimizationVisit();
                return false;
            }

            return true;
        }
    }
}
